<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="考试名称" prop="examName">
        <el-input
          v-model="queryParams.examName"
          placeholder="请输入考试名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="难度" prop="difficultyLevel">
        <el-select v-model="queryParams.difficultyLevel" placeholder="请选择难度" clearable style="width: 120px;">
          <el-option
            v-for="dict in difficulty_level"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="考试状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择考试状态" clearable   style="width: 120px;">
          <el-option
            v-for="dict in sys_common_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['business:exam:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:exam:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:exam:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['business:exam:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="examList" @selection-change="handleSelectionChange" row-key="id">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="考试名称" align="center" prop="examName" />
      <el-table-column label="考试开始时间" align="center" prop="startTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="考试结束时间" align="center" prop="endTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="考试时长" align="center" prop="duration" />
      <el-table-column label="难度" align="center" prop="difficultyLevel">
        <template #default="scope">
          <dict-tag :options="difficulty_level" :value="scope.row.difficultyLevel"/>
        </template>
      </el-table-column>
      <el-table-column label="考试总分数" align="center" prop="totalScore" />
      <el-table-column label="题目数" align="center" prop="totalNum" />
      <el-table-column label="考试状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="sys_common_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width"  fixed="right" width="210">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleChooseQuestion(scope.row)" v-hasPermi="['business:exam:chooseQuestion']">组卷</el-button>
          <el-button link type="primary" icon="Edit" @click="handleChoosePeople(scope.row)" v-hasPermi="['business:exam:choosePeople']">选人</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['business:exam:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['business:exam:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改考试表对话框 -->
    <el-dialog :title="title" v-model="open" width="900px" append-to-body>
      <el-form ref="examRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="考试名称" prop="examName">
          <el-input v-model="form.examName" placeholder="请输入考试名称" />
        </el-form-item>
        <el-form-item label="考试开始时间" prop="startTime">
          <el-date-picker clearable
            v-model="form.startTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择考试开始时间"
            :disabled-date="disabledStartDate"
            @change="calculateDuration">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="考试结束时间" prop="endTime">
          <el-date-picker clearable
            v-model="form.endTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择考试结束时间"
            :disabled-date="disabledEndDate"
            @change="calculateDuration">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="考试时长" prop="duration">
          <el-input v-model="form.duration" placeholder="考试时长将根据开始和结束时间自动计算" disabled />
        </el-form-item>
        <el-form-item label="难度" prop="difficultyLevel">
          <el-select v-model="form.difficultyLevel" placeholder="请选择难度">
            <el-option
              v-for="dict in difficulty_level"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="考试总分数" prop="totalScore">
          <el-input v-model="form.totalScore" placeholder="请输入考试总分数" />
        </el-form-item>
        <el-form-item label="考试状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择考试状态">
            <el-option
              v-for="dict in sys_common_status"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 选择题目对话框 -->
    <el-dialog title="选择题目" v-model="questionDialogVisible" width="1200px" append-to-body @close="handleDialogClose">
      <el-form :model="questionQueryParams" ref="questionQueryRef" :inline="true" v-show="showQuestionSearch" label-width="68px">
        <el-form-item label="题目类型" prop="questionType">
          <el-select
            v-model="questionQueryParams.questionType"
            placeholder="请选择题目类型"
            clearable
            style="width: 120px"
          >
            <el-option
              v-for="dict in question_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="题目难度" prop="difficultyLevel">
          <el-select
            v-model="questionQueryParams.difficultyLevel"
            placeholder="请选择题目难度"
            clearable
            style="width: 120px"
          >
            <el-option
              v-for="dict in difficulty_level"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuestionQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuestionQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table
        v-loading="questionLoading"
        :data="questionList"
        @selection-change="handleQuestionSelectionChange"
        row-key="id"
        ref="questionTableRef"
      >
        <el-table-column type="selection" width="55" align="center" :reserve-selection="true" />
        <el-table-column label="题目类型" align="center" prop="questionType">
          <template #default="scope">
            <dict-tag :options="question_type" :value="scope.row.questionType" />
          </template>
        </el-table-column>
        <el-table-column label="题目内容" align="center" prop="questionContent" />
        <el-table-column label="题目难度" align="center" prop="difficultyLevel">
          <template #default="scope">
            <dict-tag
              :options="difficulty_level"
              :value="scope.row.difficultyLevel"
            />
          </template>
        </el-table-column>
        <el-table-column label="正确答案" align="center" prop="correctAnswer" />
        <el-table-column label="题目分值" align="center" prop="score" />
      </el-table>

      <pagination
        v-show="questionTotal > 0"
        :total="questionTotal"
        v-model:page="questionQueryParams.pageNum"
        v-model:limit="questionQueryParams.pageSize"
        @pagination="getQuestionList"
      />

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="saveSelectedQuestions">确 定</el-button>
          <el-button @click="questionDialogVisible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 选择人员对话框 -->
    <el-dialog :title="'选择人员 - ' + currentExamName" v-model="peopleDialogVisible" width="800px" append-to-body>
      <el-table
        v-loading="peopleLoading"
        :data="peopleList"
        @selection-change="handlePeopleSelectionChange"
        row-key="userId"
        ref="peopleTableRef"
      >
        <el-table-column type="selection" width="55" align="center" :reserve-selection="true" />
        <el-table-column label="用户编号" align="center" prop="userId" />
        <el-table-column label="用户名称" align="center" prop="userName" />
        <el-table-column label="手机号码" align="center" prop="phonenumber" />
        <el-table-column label="邮箱" align="center" prop="email" />
      </el-table>

      <pagination
        v-show="peopleTotal > 0"
        :total="peopleTotal"
        v-model:page="peopleQueryParams.pageNum"
        v-model:limit="peopleQueryParams.pageSize"
        @pagination="getPeopleList"
      />

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="saveSelectedPeople">确 定</el-button>
          <el-button @click="peopleDialogVisible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Exam">
import { listExam, getExam, delExam, addExam, updateExam,   listUser, saveExamUsers } from "@/api/business/exam";
import { saveExamQuestions } from "@/api/business/examquestion";
import { listQuestion } from "@/api/business/question";
const { proxy } = getCurrentInstance();
const { sys_common_status, difficulty_level, question_type } = proxy.useDict('sys_common_status', 'difficulty_level', 'question_type');

const examList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    examName: null,
    startTime: null,
    endTime: null,
    duration: null,
    difficultyLevel: null,
    totalScore: null,
    status: null,
  },
  rules: {
    examName: [
      { required: true, message: "考试名称不能为空", trigger: "blur" }
    ],
    startTime: [
      { required: true, message: "考试开始时间不能为空", trigger: "blur" },
      { validator: validateStartTime, trigger: "change" }
    ],
    endTime: [
      { required: true, message: "考试结束时间不能为空", trigger: "blur" },
      { validator: validateEndTime, trigger: "change" }
    ],
    duration: [
      { required: true, message: "考试时长不能为空", trigger: "blur" }
    ],
    difficultyLevel: [
      { required: true, message: "难度不能为空", trigger: "change" }
    ],
    status: [
      { required: true, message: "考试状态不能为空", trigger: "change" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

// 题目选择相关变量
const questionDialogVisible = ref(false);
const questionLoading = ref(false);
const showQuestionSearch = ref(true);
const questionList = ref([]);
const questionTotal = ref(0);
const selectedQuestions = ref([]);
const currentExamId = ref(null);
const questionTableRef = ref(null);  // 添加表格引用

const questionQueryParams = ref({
  type:"exam",
  examId: null,
  pageNum: 1,
  pageSize: 10,
  questionType: null,
  difficultyLevel: null,
});

// 选择人员相关数据
const peopleDialogVisible = ref(false);
const peopleLoading = ref(false);
const peopleList = ref([]);
const peopleTotal = ref(0);
const peopleTableRef = ref();
const selectedPeople = ref([]);
const currentExamIdForPeople = ref(null);
const currentExamName = ref('');

const peopleQueryParams = ref({
  pageNum: 1,
  pageSize: 10,
  userName: undefined,
  phonenumber: undefined
});

/** 查询考试表列表 */
function getList() {
  loading.value = true;
  listExam(queryParams.value).then(response => {
    examList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    examName: null,
    startTime: null,
    endTime: null,
    duration: null,
    difficultyLevel: null,
    totalScore: null,
    status: null,
    createTime: null,
    updateTime: null
  };
  proxy.resetForm("examRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加考试表";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getExam(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改考试表";
  });
}

/** 提交按钮 */
function submitForm() {
  console.log(form.value)
  proxy.$refs["examRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateExam(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addExam(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除考试表编号为"' + _ids + '"的数据项？').then(function() {
    return delExam(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('business/exam/export', {
    ...queryParams.value
  }, `exam_${new Date().getTime()}.xlsx`)
}

/** 计算考试时长（分钟） */
function calculateDuration() {
  if (form.value.startTime && form.value.endTime) {
    const start = new Date(form.value.startTime);
    const end = new Date(form.value.endTime);
    
    if (start >= end) {
      proxy.$modal.msgError("开始时间必须小于结束时间");
      form.value.endTime = null;
      form.value.duration = null;
      return;
    }
    
    // 计算时间差（毫秒）并转换为分钟
    const diffMinutes = Math.floor((end - start) / (1000 * 60));
    form.value.duration = diffMinutes;
  }
}

/** 验证开始时间 */
function validateStartTime(rule, value, callback) {
  if (form.value.endTime && value >= form.value.endTime) {
    callback(new Error("开始时间必须小于结束时间"));
  } else {
    callback();
  }
}

/** 验证结束时间 */
function validateEndTime(rule, value, callback) {
  if (form.value.startTime && value <= form.value.startTime) {
    callback(new Error("结束时间必须大于开始时间"));
  } else {
    callback();
  }
}

/** 禁用开始时间选择（只能选择当前时间之后的时间） */
function disabledStartDate(time) {
  return time.getTime() < Date.now() - 8.64e7; // 禁用今天之前的时间
}

/** 禁用结束时间选择（只能选择开始时间之后的时间） */
function disabledEndDate(time) {
  // if (form.value.startTime) {
  //   const startTime = new Date(form.value.startTime);
  //   return time.getTime() <= startTime.getTime();
  // }
  return time.getTime() < Date.now() - 8.64e7; // 如果没有开始时间，则禁用今天之前的时间
}

/** 查询题目列表 */
function getQuestionList() {
  questionLoading.value = true;
  listQuestion(questionQueryParams.value).then(response => {
    questionList.value = response.rows;
    questionTotal.value = response.total;
    questionLoading.value = false;
    
    // 在数据加载完成后，根据choose字段设置选中状态
    nextTick(() => {
      // 先处理选中的题目ID
      questionList.value.forEach(row => {
        // 检查choose字段，处理不同的可能值类型
        console.log('choose', row.choose, typeof row.choose);
        const isChosen = row.choose === true || row.choose === 'true' || row.choose === 1 || row.choose === '1';
        if (isChosen) {
          // 如果是新选中的题目，添加到selectedQuestions中
          if (!selectedQuestions.value.includes(row.id)) {
            selectedQuestions.value.push(row.id);
          }
        }
      });
      
      // 然后尝试设置表格选中状态
      if (questionTableRef.value) {
        // 先清除所有选择
        questionTableRef.value.clearSelection();
        
        // 然后根据selectedQuestions设置选中状态
        questionList.value.forEach(row => {
          if (selectedQuestions.value.includes(row.id)) {
            questionTableRef.value.toggleRowSelection(row, true);
          }
        });
      }
    });
  });
}

/** 打开选择题目对话框 */
function handleChooseQuestion(row) {
  currentExamId.value = row.id;
  questionQueryParams.value.examId = row.id;
  questionQueryParams.value.pageNum = 1;  // 重置为第1页
  questionDialogVisible.value = true;
  selectedQuestions.value = [];  // 清空之前的选择
  
  // 延迟加载题目列表，确保对话框已完全打开
  setTimeout(() => {
    getQuestionList();
  }, 500);
}

/** 搜索题目按钮操作 */
function handleQuestionQuery() {
  questionQueryParams.value.pageNum = 1;
  questionQueryParams.value.examId = currentExamId.value;
  getQuestionList();
}

/** 重置题目查询按钮操作 */
function resetQuestionQuery() {
  proxy.resetForm("questionQueryRef");
  questionQueryParams.value.examId = currentExamId.value;
  handleQuestionQuery();
}

/** 题目多选框选中数据 */
function handleQuestionSelectionChange(selection) {
  // 获取当前页所有题目的ID
  const currentPageIds = questionList.value.map(item => item.id);
  
  // 从已选中的题目中移除当前页的题目
  selectedQuestions.value = selectedQuestions.value.filter(id => !currentPageIds.includes(id));
  
  // 添加当前页新选中的题目
  selection.forEach(item => {
    if (!selectedQuestions.value.includes(item.id)) {
      selectedQuestions.value.push(item.id);
    }
  });
  
  // 添加当前页中标记为true但未选中的题目
  questionList.value.forEach(item => {
    const isChosen = item.choose === true || item.choose === 'true' || item.choose === 1 || item.choose === '1';
    if (isChosen && !selectedQuestions.value.includes(item.id)) {
      selectedQuestions.value.push(item.id);
      // 如果表格中有这一行，确保它被选中
      if (questionTableRef.value) {
        questionTableRef.value.toggleRowSelection(item, true);
      }
    }
  });
  
  console.log('当前选中的题目:', selectedQuestions.value);
}

/** 保存选中的题目 */
function saveSelectedQuestions() {
  if (selectedQuestions.value.length === 0) {
    proxy.$modal.msgError("请至少选择一道题目");
    return;
  }

  // 计算选中题目的总分
  const totalScore = questionList.value
    .filter(question => selectedQuestions.value.includes(question.id))
    .reduce((sum, question) => sum + (parseFloat(question.score) || 0), 0);

  const data = {
    examId: currentExamId.value,
    questionIds: selectedQuestions.value,
    totalScore: totalScore
  };
  
  console.log('提交的数据:', data);

  saveExamQuestions(data).then(response => {
    proxy.$modal.msgSuccess("保存成功");
    questionDialogVisible.value = false;
    selectedQuestions.value = [];  // 清空选择
    // 更新考试列表
    getList();
  });
}

/** 关闭对话框时清空选择 */
function handleDialogClose() {
  selectedQuestions.value = [];
  if (questionTableRef.value) {
    questionTableRef.value.clearSelection();
  }
}

/** 查询人员列表 */
function getPeopleList() {
  peopleLoading.value = true;
  
  // 确保查询参数中包含当前考试ID
  peopleQueryParams.value.examId = currentExamIdForPeople.value;
  
  // 从接口获取用户数据
  listUser(peopleQueryParams.value).then(response => {
    peopleList.value = response.rows;
    peopleTotal.value = response.total;
    peopleLoading.value = false;
    
    // 设置选中状态
    nextTick(() => {
      if (peopleTableRef.value) {
        peopleTableRef.value.clearSelection();
        peopleList.value.forEach(row => {
          if (selectedPeople.value.includes(row.userId)) {
            peopleTableRef.value.toggleRowSelection(row, true);
          }
        });
      }
    });
  });
}

/** 打开选择人员对话框 */
function handleChoosePeople(row) {
  currentExamIdForPeople.value = row.id;
  currentExamName.value = row.examName;
  peopleQueryParams.value.pageNum = 1;
  peopleQueryParams.value.examId = row.id;  // 设置当前考试ID
  peopleDialogVisible.value = true;
  selectedPeople.value = [];
  
  // 延迟加载人员列表，确保对话框已完全打开
  setTimeout(() => {
    getPeopleList();
  }, 500);
}

/** 搜索人员按钮操作 */
function handlePeopleQuery() {
  peopleQueryParams.value.pageNum = 1;
  peopleQueryParams.value.examId = currentExamIdForPeople.value;  // 确保搜索时包含当前考试ID
  getPeopleList();
}

/** 重置人员搜索按钮操作 */
function resetPeopleQuery() {
  peopleQueryParams.value = {
    examId: currentExamIdForPeople.value,  // 保留当前考试ID
    pageNum: 1,
    pageSize: 10,
    userName: undefined,
    phonenumber: undefined
  };
  handlePeopleQuery();
}

/** 人员多选框选中数据 */
function handlePeopleSelectionChange(selection) {
  // 获取当前页所有人员的ID
  const currentPageIds = peopleList.value.map(item => item.userId);
  
  // 从已选中的人员中移除当前页的人员
  selectedPeople.value = selectedPeople.value.filter(id => !currentPageIds.includes(id));
  
  // 添加当前页新选中的人员
  selection.forEach(item => {
    if (!selectedPeople.value.includes(item.userId)) {
      selectedPeople.value.push(item.userId);
    }
  });
  
  console.log('当前选中的人员:', selectedPeople.value);
}

/** 保存选中的人员 */
function saveSelectedPeople() {
  if (selectedPeople.value.length === 0) {
    proxy.$modal.msgError("请至少选择一名人员");
    return;
  }

  const data = {
    examId: currentExamIdForPeople.value,
    userIds: selectedPeople.value
  };
  
  console.log('提交的人员数据:', data);

  saveExamUsers(data).then(response => {
    proxy.$modal.msgSuccess("保存成功");
    peopleDialogVisible.value = false;
    selectedPeople.value = [];
    // 更新考试列表
    getList();
  });
}

getList();
</script>
